import React, { useState, useEffect } from 'react';
import { Button, Modal, Form, Input, Row, Col, Select, ConfigProvider } from 'antd';
import TRNotification from '#/utils/notification.js';
import { HttpCode } from '#/utils/contacts.js';
import planIcon from '@/assets/img/plan_icon.png';
import type { IApplyType, IDataSourceType } from '../../type';
import { IOperationType } from '../../type';
import zhCN from 'antd/lib/locale/zh_CN';
import styles from './index.less';
import type { ProvinceType } from '@/hooks/useRequestPowerAfterInit';

interface IProps {
  /**
   * 操作类型
   */
  operationType: IOperationType;
  /**
   * 数据
   */
  data: IDataSourceType;
  /**
   * 交易单元
   */
  marketList: ProvinceType[];

  onPress: (data: Record<string, any>) => void;
  onOk: (params: IApplyType) => void;
}

const ApplyModalComponent = (props: IProps) => {
  const { onOk, onPress, operationType = IOperationType.ADD, data } = props;
  const [form] = Form.useForm();
  const [visible, setVisible] = useState<boolean>(true);
  const [loading, setLoading] = useState<boolean>(false);

  useEffect(() => {
    const _data: IApplyType = {
      description: data?.description ? data?.description : undefined,
      visible: operationType === IOperationType.ADD ? 1 : data?.visible ? 1 : 0,
      explain: data && data.explain ? data?.explain : undefined,
    };
    form && form.setFieldsValue(_data);
  }, [data]);

  // 取消
  const _onCancel = () => {
    setVisible(false);
    onPress({ index: 0 });
  };

  // 确认
  const _onOk = async () => {
    form &&
      form.validateFields().then(async (value) => {
        setLoading(true);
        const _value: IApplyType = {
          ...value,
          id: operationType === IOperationType.ADD ? undefined : data?.id,
        };
        const res: any = await onOk(_value);
        if (res && res.statusCode === HttpCode.SUCCESS) {
          setVisible(false);
          onPress({ index: 1, statusCode: HttpCode.SUCCESS });
        }
        setLoading(false);
      });
  };

  const footerRender = () => {
    return [
      <Button key="dtest1" onClick={_onCancel} loading={loading}>
        取消
      </Button>,
      <Button key="dtest2" type="primary" onClick={_onOk} loading={loading}>
        确定
      </Button>,
    ];
  };

  return (
    <Modal
      className={styles.modal}
      centered
      width={492}
      maskClosable={false}
      visible={visible}
      title={
        <div className={styles.titleDiv}>
          <img src={planIcon} className={styles.titleLogo} />
          <span className={styles.title}>{operationType === '1' ? '新增' : '编辑'}</span>
        </div>
      }
      onCancel={_onCancel}
      footer={footerRender()}
    >
      <ConfigProvider locale={zhCN}>
        <div className={styles.container}>
          <Form
            className={styles.form}
            form={form}
            name="apply"
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 20 }}
            colon={false}
            labelAlign="left"
            autoComplete="off"
            requiredMark={false}
          >
            <Row className={styles.row}>
              <Col span={24}>
                <Form.Item
                  name="explain"
                  label="交易中心"
                  rules={[{ required: true, message: '请选择交易中心' }]}
                >
                  <Select
                    options={props.marketList || []}
                    placeholder="请选择交易单元"
                    showSearch
                    filterOption={(input: string, option: any) => {
                      return (option?.label).toLowerCase().includes(input.toLowerCase());
                    }}
                  />
                </Form.Item>
                <Form.Item
                  name="description"
                  label="文件类别"
                  rules={[
                    { required: true, message: '请填写文件类别' },
                    { max: 15, message: '文件类别不可超过15个字符' },
                    {
                      validator: (_, value) => {
                        if (typeof value === 'string' && value.trim() === '') {
                          return Promise.reject('请填写文件类别');
                        }
                        return Promise.resolve();
                      },
                    },
                  ]}
                >
                  <Input placeholder="文件类别" />
                </Form.Item>
              </Col>
            </Row>
          </Form>
        </div>
      </ConfigProvider>
    </Modal>
  );
};

class ApplyModal {
  __key__ = '';

  show = (props: any) => {
    return new Promise((resolve) => {
      if (this.__key__ !== '') return;
      this.__key__ = String(Date.now());
      TRNotification.add({
        key: this.__key__,
        content: (
          <ApplyModalComponent
            {...props}
            onPress={(result: any) => {
              TRNotification.remove(this.__key__);
              this.__key__ = '';
              resolve(result);
            }}
          />
        ),
        duration: null,
        dismiss: this.dismiss,
      });
    });
  };

  dismiss = () => {
    if (this.__key__.length > 0) {
      TRNotification.remove(this.__key__);
      this.__key__ = '';
    }
  };
}

export default new ApplyModal();
